package com.jason.campusinn.view;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.ColorDrawable;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.lidroid.xutils.util.LogUtils;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.sina.weibo.sdk.api.ImageObject;
import com.sina.weibo.sdk.api.TextObject;
import com.sina.weibo.sdk.api.WebpageObject;
import com.sina.weibo.sdk.api.WeiboMessage;
import com.sina.weibo.sdk.api.WeiboMultiMessage;
import com.sina.weibo.sdk.api.share.BaseResponse;
import com.sina.weibo.sdk.api.share.IWeiboHandler;
import com.sina.weibo.sdk.api.share.IWeiboShareAPI;
import com.sina.weibo.sdk.api.share.SendMessageToWeiboRequest;
import com.sina.weibo.sdk.api.share.SendMultiMessageToWeiboRequest;
import com.sina.weibo.sdk.api.share.WeiboShareSDK;
import com.sina.weibo.sdk.auth.AuthInfo;
import com.sina.weibo.sdk.auth.Oauth2AccessToken;
import com.sina.weibo.sdk.auth.WeiboAuthListener;
import com.sina.weibo.sdk.auth.sso.SsoHandler;
import com.sina.weibo.sdk.constant.WBConstants;
import com.sina.weibo.sdk.exception.WeiboException;
import com.sina.weibo.sdk.utils.Utility;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.SendMessageToWX;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.mm.sdk.openapi.WXMediaMessage;
import com.tencent.mm.sdk.openapi.WXWebpageObject;
import com.tencent.mm.sdk.platformtools.Util;
import com.yuandian.wanna.R;
import com.yuandian.wanna.bean.initialize.LoginInfo;
import com.yuandian.wanna.constants.InterfaceConstants;
import com.yuandian.wanna.constants.ThirdConstants;
import com.yuandian.wanna.utils.AccessTokenKeeper;
import com.yuandian.wanna.utils.ImageDownloader;
import com.yuandian.wanna.utils.LogUtil;

import java.net.URL;
import java.util.logging.Handler;

/**
 * Created by yuandian on 2015/5/18.
 */
public class SharePopupWindow extends PopupWindow implements View.OnClickListener, IWeiboHandler.Response {

    private RelativeLayout shareSina;
    private RelativeLayout shareFriends;
    private RelativeLayout shareWechat;
    private RelativeLayout shareSms;
    private TextView shareCancel;
    private ImageView img_share_cancel;
    private Activity context;
    private String html = "";
    private String title = "魔幻工厂";
    private String content = "朋友圈里就数你穿衣服最讲究～我发现一款超棒的定制APP，第一时间就想到你，快去下载吧!";
    private String imgUrl = null;  //分享的图片url路径
    private Bitmap imgBitmap = null;   //分享的图片Bitmap
    private int mFlag;//标志位 1:来自聊天添加好友；2：来自普通分享
    private View view;
    private String descriptionToDownload = "朋友圈里就数你穿衣服最讲究～我发现一款超棒的定制APP，第一时间就想到你，快去下载吧";
    private String descriptionToAddFriends = "你干嘛呢，我在魔幻工厂APP定制衣服呢，最相信你的眼光了，快来帮我参考一下～";

    private final int THUMB_SIZE = 150; //微信分享的缩略图大小

    protected LoadingDialog mLoadingDialog;

    /**
     * 分享网页控件
     */
    private WBShareItemView mShareWebPageView;


    private IWeiboShareAPI iWeiboShareAPI = null;//微博分享API
    private IWXAPI iWxapi = null;
    private SsoHandler mSsoHandler = null;

    /**
     * 设置分享的图片url路径
     *
     * @param imgUrl 图片原路径
     */
    public void setImgUrl(String imgUrl) {
        this.imgUrl = imgUrl;
        LogUtil.d("image_url = " + this.imgUrl);
        //设置BitMap为空
        if (this.imgBitmap != null) {
            this.imgBitmap.recycle();
            this.imgBitmap = null;
        }
    }

    /**
     * 设置分享的图片BitMap
     *
     * @param bitmap 图片BitMap
     */
    public void setImgBitmap(Bitmap bitmap) {
        //复制Bitmap
        this.imgBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight());
        //url置空
        this.imgUrl = null;
    }

    public SharePopupWindow(Activity context, int mFlag, String content) {

        this.context = context;
        this.content = content;
        this.mFlag = mFlag;
        html = InterfaceConstants.SHARE_DOWNLOAD.replace("MEMBER_ID", LoginInfo.getInstance(context).getMemberId());
        LogUtil.d("分享下载地址==========" + html);


        mLoadingDialog = new LoadingDialog(this.context);

        //初始化页面
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        view = inflater.inflate(R.layout.activity_share, null);
        shareFriends = (RelativeLayout) view.findViewById(R.id.rela_share_friends);
        shareSina = (RelativeLayout) view.findViewById(R.id.rela_share_sina);
        shareWechat = (RelativeLayout) view.findViewById(R.id.rela_share_wechat);
        shareSms = (RelativeLayout) view.findViewById(R.id.rela_share_sms);
        shareCancel = (TextView) view.findViewById(R.id.share_cancel_text);
        img_share_cancel = (ImageView) view.findViewById(R.id.img_share_cancel);
        img_share_cancel.setOnClickListener(this);
        shareCancel.setOnClickListener(this);
        shareSms.setOnClickListener(this);
        shareWechat.setOnClickListener(this);
        shareSina.setOnClickListener(this);
        shareFriends.setOnClickListener(this);
        setContentView(view);

        // 设置SelectPicPopupWindow弹出窗体的宽
        this.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        this.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        // 设置SelectPicPopupWindow弹出窗体可点击
        this.setFocusable(true);
        // 设置SelectPicPopupWindow弹出窗体动画效果
        this.setAnimationStyle(R.style.popupStyle);
        // 实例化一个ColorDrawable颜色为半透明
        ColorDrawable dw = new ColorDrawable(0xB0FFFFFF);
        // 设置SelectPicPopupWindow弹出窗体的背景
        this.setBackgroundDrawable(dw);
        this.setOutsideTouchable(true);
        this.update();


        //实例化微博分享api
        iWeiboShareAPI = WeiboShareSDK.createWeiboAPI(context, ThirdConstants.SINA_APP_KEY);
        iWeiboShareAPI.registerApp();

        //实例化微信分享api
        iWxapi = WXAPIFactory.createWXAPI(context, ThirdConstants.WX_APP_KEY, true);
        iWxapi.registerApp(ThirdConstants.WX_APP_KEY);

    }


    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.rela_share_friends:
                friendShare();//分享到微信朋友圈
                break;
            case R.id.rela_share_wechat:
                wechatShare();//分享到微信好友
                break;
            case R.id.rela_share_sina:
                sendMultiMessage(true, true, false);
//                sendSingleMessage();
                break;
            case R.id.rela_share_sms://分享到短信
                sendSMS(descriptionToAddFriends + html);
                break;
            case R.id.share_cancel_text://取消分享
                dismiss();
                break;
            case R.id.img_share_cancel:
                dismiss();
                break;
        }
    }

    /**
     * 发送短信
     *
     * @param smsBody
     */
    private void sendSMS(String smsBody) {
        Uri smsToUri = Uri.parse("smsto:");
        Intent intent = new Intent(Intent.ACTION_SENDTO, smsToUri);
        intent.putExtra("sms_body", smsBody);
        context.startActivity(intent);
    }


    /**
     * 创建文字消息对象。
     *
     * @return 文字消息对象。
     */
    private TextObject getTextObj() {
        TextObject textObject = new TextObject();
        textObject.text = content + html;
        return textObject;
    }

//    /**
//     * 创建图片消息对象。
//     *
//     * @return 图片消息对象。
//     */
//    private ImageObject getImageObj() {
//        ImageObject imageObject = new ImageObject();
//        Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.icon_logo);
//        imageObject.setImageObject(bitmap);
//        return imageObject;
//    }

    /**
     * 创建图片消息对象,并分享到微博。
     *
     */
    private void loadImageAndShare(final WeiboMultiMessage weiboMessage) {
        final ImageObject imageObject = new ImageObject();
        LogUtil.d("Here in ----weibo --E");
        //通过Bitmap获取图片
        if (this.imgBitmap != null) {
            Bitmap thumb = Bitmap.createScaledBitmap(this.imgBitmap, THUMB_SIZE, THUMB_SIZE, true);
            this.imgBitmap.recycle();
            imageObject.setImageObject(thumb);
            weiboMessage.imageObject = imageObject;
            sinaShare(weiboMessage);
        }
        else if (this.imgUrl != null) {
            mLoadingDialog.show();
            LogUtil.d("Here in ----weibo --F");
            if (this.imgUrl.startsWith("http://7xjold.com1")&&(this.imgUrl.endsWith(".jpg") || this.imgUrl.endsWith(".png"))) {
                LogUtil.d("Here in ----weibo --G");
                //获取150*150的缩略图
                this.imgUrl = this.imgUrl + "?imageView2/1/w/150/h/150";
                LogUtil.d("image_url ShareUrl = " + this.imgUrl);
            }
            LogUtil.d("Here in ----weibo --H");
            ImageDownloader.getInstance(context).loadImage(this.imgUrl, new ImageLoadingListener() {
                @Override
                public void onLoadingStarted(String s, View view) {

                }

                @Override
                public void onLoadingFailed(String s, View view, FailReason failReason) {

                }

                @Override
                public void onLoadingComplete(String s, View view, Bitmap bitmap) {
                    LogUtil.d("Here in ----weibo --I");
                    if (mLoadingDialog.isShowing()) {
                        mLoadingDialog.dismiss();
                    }
                    //设置150*150的略缩图
                    Bitmap bump = Bitmap.createScaledBitmap(bitmap, THUMB_SIZE, THUMB_SIZE, true);
//                    bitmap.recycle();
                    Bitmap thumb = setWhiteBackGround(bump);
                    bump.recycle();
                    bitmap.recycle();
                    imageObject.setImageObject(thumb);
                    weiboMessage.imageObject = imageObject;
                    sinaShare(weiboMessage);
                    LogUtil.d("Here in ----weibo --J");
                }

                @Override
                public void onLoadingCancelled(String s, View view) {

                }
            });
        }
        else{
            LogUtil.d("Here in ----weibo --K");
            Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.icon_logo);
            imageObject.setImageObject(bitmap);
            weiboMessage.imageObject = imageObject;
            sinaShare(weiboMessage);
        }
    }


    /**
     * 创建多媒体（网页）消息对象。
     *
     * @return 多媒体（网页）消息对象。
     */
    private WebpageObject getWebpageObj() {

        WebpageObject mediaObject = new WebpageObject();
        mediaObject.identify = Utility.generateGUID();
        mediaObject.title = title;
        mediaObject.description = content;

        // 设置 Bitmap 类型的图片到视频对象里
        mediaObject.setThumbImage(BitmapFactory.decodeResource(context.getResources(), R.drawable.icon_logo));
        mediaObject.actionUrl = html;
        mediaObject.defaultText = "";
        return mediaObject;
    }

    private Bitmap convertResToBm(int id) {
        BitmapFactory.Options option = new BitmapFactory.Options();
        option.inSampleSize = 2; // 将原图缩小四分之一读取
        option.inJustDecodeBounds = false;
        Bitmap bm = BitmapFactory.decodeResource(context.getResources(), id, option);

        return ThumbnailUtils.extractThumbnail(bm, 114, 114); // 将图片的大小限定在480*800
    }

    /**
     * 接收微客户端博请求的数据。 当微博客户端唤起当前应用并进行分享时，该方法被调用。
     *
     * @param baseResp 微博请求数据对象
     * @see {@link IWeiboShareAPI#handleWeiboRequest}
     */
    @Override
    public void onResponse(BaseResponse baseResp) {
        switch (baseResp.errCode) {
            case WBConstants.ErrorCode.ERR_OK:
                Toast.makeText(context, "分享成功", Toast.LENGTH_LONG).show();
                break;
            case WBConstants.ErrorCode.ERR_CANCEL:
                Toast.makeText(context, "分享取消", Toast.LENGTH_LONG).show();
                break;
            case WBConstants.ErrorCode.ERR_FAIL:
                Toast.makeText(context, "分享失败" + "Error Message: " + baseResp.errMsg, Toast.LENGTH_LONG).show();
                break;
        }
        dismiss();
    }

    private void sendSingleMessage() {

        // 1. 初始化微博的分享消息
        // 用户可以分享文本、图片、网页、音乐、视频中的一种
        WeiboMessage weiboMessage = new WeiboMessage();

        weiboMessage.mediaObject = getWebpageObj();

        // 2. 初始化从第三方到微博的消息请求
        SendMessageToWeiboRequest request = new SendMessageToWeiboRequest();
        // 用transaction唯一标识一个请求
        request.transaction = String.valueOf(System.currentTimeMillis());
        request.message = weiboMessage;

        // 3. 发送请求消息到微博，唤起微博分享界面
        iWeiboShareAPI.sendRequest(context, request);
    }

    /**
     * 第三方应用发送请求消息到微博，唤起微博分享界面。
     * 注意：当 {@link IWeiboShareAPI#getWeiboAppSupportAPI()} >= 10351 时，支持同时分享多条消息，
     * 同时可以分享文本、图片以及其它媒体资源（网页、音乐、视频、声音中的一种）。
     *
     * @param hasText    分享的内容是否有文本
     * @param hasImage   分享的内容是否有图片
     * @param hasWebpage 分享的内容是否有网页
     */
    private void sendMultiMessage(boolean hasText, boolean hasImage, boolean hasWebpage) {
        LogUtil.d("Here in ----weibo --A");
        // 1. 初始化微博的分享消息
        WeiboMultiMessage weiboMessage = new WeiboMultiMessage();
        if (hasText) {
            LogUtil.d("Here in ----weibo --B");
            weiboMessage.textObject = getTextObj();
        }

        // 用户可以分享其它媒体资源（网页、音乐、视频、声音中的一种）
        if (hasWebpage) {
            weiboMessage.mediaObject = getWebpageObj();
        }
        if (hasImage) {
            LogUtil.d("Here in ----weibo --C");
//            weiboMessage.imageObject = getImageObj();
            loadImageAndShare(weiboMessage);
            LogUtil.d("Here in ----weibo --D");
        }else{
            sinaShare(weiboMessage);
        }

//        // 2. 初始化从第三方到微博的消息请求
//        SendMultiMessageToWeiboRequest request = new SendMultiMessageToWeiboRequest();
//        // 用transaction唯一标识一个请求
//        request.transaction = String.valueOf(System.currentTimeMillis());
//        request.multiMessage = weiboMessage;


/*//         3. 发送请求消息到微博，唤起微博分享界面(before//)
//        if (mShareType == SHARE_CLIENT) {
//            mWeiboShareAPI.sendRequest(WBShareActivity.this, request);
//        }
//        else if (mShareType == SHARE_ALL_IN_ONE) {*/



//        AuthInfo authInfo = new AuthInfo(context, ThirdConstants.SINA_APP_KEY, ThirdConstants.REDIRECT_URL, ThirdConstants.SCOPE);
//        Oauth2AccessToken accessToken = AccessTokenKeeper.readAccessToken(context.getApplicationContext());
//        String token = "";
//        if (accessToken != null) {
//            token = accessToken.getToken();
//        }
//        iWeiboShareAPI.sendRequest(context, request, authInfo, token, new WeiboAuthListener() {
//            @Override
//            public void onWeiboException(WeiboException e) {
//                if (mLoadingDialog.isShowing()) {
//                    mLoadingDialog.dismiss();
//                }
//                Toast.makeText(context, "Auth exception : " + e.getMessage(), Toast.LENGTH_LONG).show();
//            }
//
//            @Override
//            public void onComplete(Bundle bundle) {
//                if (mLoadingDialog.isShowing()) {
//                    mLoadingDialog.dismiss();
//                }
//                Oauth2AccessToken newToken = Oauth2AccessToken.parseAccessToken(bundle);
//                AccessTokenKeeper.writeAccessToken(context.getApplicationContext(), newToken);
////                Toast.makeText(context.getApplicationContext(), "onAuthorizeComplete token = " + newToken.getToken(), Toast.LENGTH_LONG).show();
//            }
//
//            @Override
//            public void onCancel() {
//                if (mLoadingDialog.isShowing()) {
//                    mLoadingDialog.dismiss();
//                }
//                Toast.makeText(context, "微博取消授权", Toast.LENGTH_LONG).show();
//            }
//        });
//        }
    }


//    /**
//     * 微信分享 （这里仅提供一个分享网页的示例，其它请参看官网示例代码）
//     */
//    private void wechatShare() {
//        if (!iWxapi.isWXAppInstalled()) {
//            Toast.makeText(context, "您还未安装微信客户端",
//                    Toast.LENGTH_SHORT).show();
//            return;
//        }
//        WXWebpageObject webpage = new WXWebpageObject();
//        webpage.webpageUrl = html;//这里填写链接url
//        WXMediaMessage msg = new WXMediaMessage(webpage);
//        msg.title = "";//这里填写标题
//        msg.description = content;//这里填写内容
//        //这里替换一张自己工程里的图片资源
//        Bitmap thumb = BitmapFactory.decodeResource(context.getResources(), R.drawable.icon_logo_small);
//        msg.setThumbImage(thumb);
//
//        SendMessageToWX.Req req = new SendMessageToWX.Req();
//        req.transaction = String.valueOf(System.currentTimeMillis());
//        req.message = msg;
//        req.scene = SendMessageToWX.Req.WXSceneSession;
//        iWxapi.sendReq(req);
//    }

    /**
     * 分享到新浪微博
     * @param weiboMessage
     */
    private void sinaShare(WeiboMultiMessage weiboMessage){
        LogUtil.d("Here in ----weibo --L");
        // 2. 初始化从第三方到微博的消息请求
        SendMultiMessageToWeiboRequest request = new SendMultiMessageToWeiboRequest();
        // 用transaction唯一标识一个请求
        request.transaction = String.valueOf(System.currentTimeMillis());
        request.multiMessage = weiboMessage;

        LogUtil.d("Here in ----weibo --M");
        AuthInfo authInfo = new AuthInfo(context, ThirdConstants.SINA_APP_KEY, ThirdConstants.REDIRECT_URL, ThirdConstants.SCOPE);
        Oauth2AccessToken accessToken = AccessTokenKeeper.readAccessToken(context.getApplicationContext());
        LogUtil.d("Here in ----weibo --N");
        String token = "";
        if (accessToken != null) {
            LogUtil.d("Here in ----weibo --O");
            token = accessToken.getToken();
        }
        LogUtil.d("Here in ----weibo --P");
        iWeiboShareAPI.sendRequest(context, request, authInfo, token, new WeiboAuthListener() {
            @Override
            public void onWeiboException(WeiboException e) {
                LogUtil.d("Here in ----weibo --Q");
//                if (mLoadingDialog.isShowing()) {
//                    mLoadingDialog.dismiss();
//                }
                Toast.makeText(context, "Auth exception : " + e.getMessage(), Toast.LENGTH_LONG).show();
            }

            @Override
            public void onComplete(Bundle bundle) {
                LogUtil.d("Here in ----weibo --R");
//                if (mLoadingDialog.isShowing()) {
//                    mLoadingDialog.dismiss();
//                }
                Oauth2AccessToken newToken = Oauth2AccessToken.parseAccessToken(bundle);
                AccessTokenKeeper.writeAccessToken(context.getApplicationContext(), newToken);
//                Toast.makeText(context.getApplicationContext(), "onAuthorizeComplete token = " + newToken.getToken(), Toast.LENGTH_LONG).show();
            }

            @Override
            public void onCancel() {
                LogUtil.d("Here in ----weibo --S");
//                if (mLoadingDialog.isShowing()) {
//                    mLoadingDialog.dismiss();
//                }
                Toast.makeText(context, "微博取消授权", Toast.LENGTH_LONG).show();
            }
        });
    }


    /**
     * 微信分享 （这里仅提供一个分享网页的示例，其它请参看官网示例代码）
     */
    private void wechatShare() {
        LogUtil.d("Here in ----A");
        if (!iWxapi.isWXAppInstalled()) {
            Toast.makeText(context, "您还未安装微信客户端",
                    Toast.LENGTH_SHORT).show();
            return;
        }
        mLoadingDialog.show();
        LogUtil.d("Here in ----B");
        WXWebpageObject webpage = new WXWebpageObject();
        webpage.webpageUrl = html;//这里填写链接url
        final WXMediaMessage msg = new WXMediaMessage(webpage);
        msg.title = "";//这里填写标题
//        msg.description = content + html;//这里填写内容
        msg.description = content;
        LogUtil.d("Here in ----C");
        //通过Bitmap获取图片
        if (this.imgBitmap != null) {
            Bitmap thumb = Bitmap.createScaledBitmap(this.imgBitmap, THUMB_SIZE, THUMB_SIZE, true);
            this.imgBitmap.recycle();
            msg.setThumbImage(thumb);
            SendMessageToWX.Req req = new SendMessageToWX.Req();
            req.transaction = String.valueOf(System.currentTimeMillis());
            req.message = msg;
            req.scene = SendMessageToWX.Req.WXSceneSession;
            iWxapi.sendReq(req);
            if (mLoadingDialog.isShowing()) {
                mLoadingDialog.dismiss();
            }
            return;
        }
        if (this.imgUrl != null) {
            LogUtil.d("Here in ----AA");
            if (this.imgUrl.startsWith("http://7xjold.com1")&&(this.imgUrl.endsWith(".jpg") || this.imgUrl.endsWith(".png"))) {
                //获取150*150的缩略图
                this.imgUrl = this.imgUrl + "?imageView2/1/w/150/h/150";
                LogUtil.d("image_url ShareUrl = " + this.imgUrl);
            }
            ImageDownloader.getInstance(context).loadImage(this.imgUrl, new ImageLoadingListener() {
                @Override
                public void onLoadingStarted(String s, View view) {

                }

                @Override
                public void onLoadingFailed(String s, View view, FailReason failReason) {

                }

                @Override
                public void onLoadingComplete(String s, View view, Bitmap bitmap) {
                    LogUtil.d("Here in ----BB");
                    //设置150*150的略缩图
                    Bitmap bump = Bitmap.createScaledBitmap(bitmap, THUMB_SIZE, THUMB_SIZE, true);
//                    bitmap.recycle();
                    Bitmap thumb = setWhiteBackGround(bump);
                    bump.recycle();
                    bitmap.recycle();
                    msg.setThumbImage(thumb);

                    SendMessageToWX.Req req = new SendMessageToWX.Req();
                    req.transaction = String.valueOf(System.currentTimeMillis());
                    req.message = msg;
                    req.scene = SendMessageToWX.Req.WXSceneSession;
                    iWxapi.sendReq(req);
                    LogUtil.d("Here in ----CC");
                    if (mLoadingDialog.isShowing()) {
                        mLoadingDialog.dismiss();
                    }
                }

                @Override
                public void onLoadingCancelled(String s, View view) {

                }
            });
        }
        if (this.imgUrl == null && this.imgBitmap == null) {
            Bitmap thumb = BitmapFactory.decodeResource(context.getResources(), R.drawable.icon_logo_small);
            msg.setThumbImage(thumb);

            SendMessageToWX.Req req = new SendMessageToWX.Req();
            req.transaction = String.valueOf(System.currentTimeMillis());
            req.message = msg;
            req.scene = SendMessageToWX.Req.WXSceneSession;
            iWxapi.sendReq(req);
            if (mLoadingDialog.isShowing()) {
                mLoadingDialog.dismiss();
            }
            return;
        }

    }

    /**
     * 过滤Bitmap黑色背景，设置背景色为白色
     * @param bitmap 原Bitmap
     * @return  处理后的Bitmap
     */
    private Bitmap setWhiteBackGround(Bitmap bitmap){
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        int length = width*height;
        int []pixels = new int[length+100];
        bitmap.getPixels(pixels,0,width,0,0,width,height);
        for(int i=0;i<length;i++){
            if(pixels[i]== 0 )
                pixels[i]=0xffffffff;
        }
        Bitmap retBitmap = Bitmap.createBitmap(pixels,0,width,width,height, Bitmap.Config.ARGB_8888);
        return retBitmap;
    }

//    /**
//     * 分享到朋友圈
//     */
//    private void friendShare(){
//        if (!iWxapi.isWXAppInstalled()) {
//            Toast.makeText(context, "您还未安装微信客户端",
//                    Toast.LENGTH_SHORT).show();
//            return;
//        }
//        WXWebpageObject webpage = new WXWebpageObject();
//        webpage.webpageUrl =html;//这里填写链接url
//        WXMediaMessage msg = new WXMediaMessage(webpage);
//        msg.title = content;
//        msg.description = content;//这里填写内容
//        //这里替换一张自己工程里的图片资源
//        Bitmap thumb = BitmapFactory.decodeResource(context.getResources(), R.drawable.icon_logo_small);
//        msg.setThumbImage(thumb);
//
//        SendMessageToWX.Req req = new SendMessageToWX.Req();
//        req.transaction = String.valueOf(System.currentTimeMillis());
//        req.message = msg;
//        req.scene=SendMessageToWX.Req.WXSceneTimeline;
//        iWxapi.sendReq(req);
//    }

    /**
     * 分享到朋友圈
     */
    private void friendShare() {
        if (!iWxapi.isWXAppInstalled()) {
            Toast.makeText(context, "您还未安装微信客户端",
                    Toast.LENGTH_SHORT).show();
            return;
        }
        mLoadingDialog.show();
        WXWebpageObject webpage = new WXWebpageObject();
        webpage.webpageUrl = html;//这里填写链接url
        final WXMediaMessage msg = new WXMediaMessage(webpage);
        msg.title = content;
        msg.description = content;//这里填写内容

        //通过Bitmap获取图片
        if (this.imgBitmap != null) {
            Bitmap thumb = Bitmap.createScaledBitmap(this.imgBitmap, THUMB_SIZE, THUMB_SIZE, true);
            this.imgBitmap.recycle();
            msg.setThumbImage(thumb);
            SendMessageToWX.Req req = new SendMessageToWX.Req();
            req.transaction = String.valueOf(System.currentTimeMillis());
            req.message = msg;
            req.scene = SendMessageToWX.Req.WXSceneTimeline;
            iWxapi.sendReq(req);
            if (mLoadingDialog.isShowing()) {
                mLoadingDialog.dismiss();
            }
            return;
        }
        if (this.imgUrl != null) {
            LogUtil.d("Here in ----AA");
            if (this.imgUrl.startsWith("http://7xjold.com1")&&(this.imgUrl.endsWith(".jpg") || this.imgUrl.endsWith(".png"))) {
                //获取150*150的缩略图
                this.imgUrl = this.imgUrl + "?imageView2/1/w/150/h/150";
                LogUtil.d("image_url ShareUrl = " + this.imgUrl);
            }
            ImageDownloader.getInstance(context).loadImage(this.imgUrl, new ImageLoadingListener() {
                @Override
                public void onLoadingStarted(String s, View view) {

                }

                @Override
                public void onLoadingFailed(String s, View view, FailReason failReason) {

                }

                @Override
                public void onLoadingComplete(String s, View view, Bitmap bitmap) {
                    LogUtil.d("Here in ----BB");
                    //设置150*150的略缩图
                    Bitmap bump = Bitmap.createScaledBitmap(bitmap, THUMB_SIZE, THUMB_SIZE, true);
//                    bitmap.recycle();
                    Bitmap thumb = setWhiteBackGround(bump);
                    bump.recycle();
                    bitmap.recycle();
                    msg.setThumbImage(thumb);
                    SendMessageToWX.Req req = new SendMessageToWX.Req();
                    req.transaction = String.valueOf(System.currentTimeMillis());
                    req.message = msg;
                    req.scene = SendMessageToWX.Req.WXSceneTimeline;
                    iWxapi.sendReq(req);
                    LogUtil.d("Here in ----CC");
                    if (mLoadingDialog.isShowing()) {
                        mLoadingDialog.dismiss();
                    }
                }

                @Override
                public void onLoadingCancelled(String s, View view) {

                }
            });
        }
        if (this.imgUrl == null && this.imgBitmap == null) {
            Bitmap thumb = BitmapFactory.decodeResource(context.getResources(), R.drawable.icon_logo_small);
            msg.setThumbImage(thumb);

            SendMessageToWX.Req req = new SendMessageToWX.Req();
            req.transaction = String.valueOf(System.currentTimeMillis());
            req.message = msg;
            req.scene = SendMessageToWX.Req.WXSceneTimeline;
            iWxapi.sendReq(req);
            if (mLoadingDialog.isShowing()) {
                mLoadingDialog.dismiss();
            }
            return;
        }

    }


}
